package org.wltea.analyzer.dic;

import org.apache.logging.log4j.Logger;
import org.elasticsearch.core.PathUtils;
import org.wltea.analyzer.help.ESPluginLoggerFactory;

import java.io.FileInputStream;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Author: dlc
 * @Date: 2022/2/9 - 14:26
 */
public class HotLoadFromMysqlThread implements Runnable{

    private static final Logger logger = ESPluginLoggerFactory.getLogger(Dictionary.class.getName());

    public static Properties properties = new Properties();
    public static Connection connection = null;

    static {
        try {

            // 获取文件路径，这个是学的他获取其他文件路径的方式
            String url = Dictionary.getSingleton().getConf_dir().toAbsolutePath().toString();

            Path path = PathUtils.get(url, "jdbc.properties");
            // 载入
            properties.load(new FileInputStream(path.toFile()));

            // 获取配置文件位置
            connection =  DriverManager.getConnection(
                    properties.getProperty("jdbc.url"),
                    properties.getProperty("jdbc.user"),
                    properties.getProperty("jdbc.password")
            );
            logger.info("init mysql connection completed......");

        } catch (Exception e) {
            logger.error("init mysql connection exception.....");
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        while(true) {
            logger.info("start reload data from mysql ......");
            // 调用reaload方法。
            Dictionary.getSingleton().reLoadMainDict();

            // 五秒钟加载一次
            try {
                  Thread.sleep(Integer.valueOf(String.valueOf(properties.getProperty("jdbc.reload.interval"))));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
